package com.snakegame.entity;

import com.snakegame.config.Direction;

import java.util.LinkedList;
import java.util.List;

/**
 * 蛇类，代表游戏中的蛇
 */
public class Snake {
    private List<Point> body;
    private Direction direction;
    private Direction nextDirection;
    private boolean growing;
    private int growAmount;
    
    public Snake(Point startPosition, Direction startDirection) {
        body = new LinkedList<>();
        body.add(startPosition);
        direction = startDirection;
        nextDirection = startDirection;
        growing = false;
        growAmount = 0;
    }
    
    public void move() {
        Point head = getHead();
        direction = nextDirection;
        
        Point newHead = new Point(head.x, head.y);
        
        switch (direction) {
            case UP:
                newHead.y--;
                break;
            case DOWN:
                newHead.y++;
                break;
            case LEFT:
                newHead.x--;
                break;
            case RIGHT:
                newHead.x++;
                break;
        }
        
        body.add(0, newHead);
        
        if (growing) {
            growAmount--;
            if (growAmount == 0) {
                growing = false;
            }
        } else {
            body.remove(body.size() - 1);
        }
    }
    
    public void grow() {
        growing = true;
        growAmount += 3; // 每次吃食物增长3个单位
    }
    
    public void setDirection(Direction newDirection) {
        // 确保蛇不能直接反向移动
        if ((direction == Direction.UP && newDirection != Direction.DOWN) ||
            (direction == Direction.DOWN && newDirection != Direction.UP) ||
            (direction == Direction.LEFT && newDirection != Direction.RIGHT) ||
            (direction == Direction.RIGHT && newDirection != Direction.LEFT)) {
            nextDirection = newDirection;
        }
    }
    
    public boolean checkSelfCollision() {
        Point head = getHead();
        for (int i = 1; i < body.size(); i++) {
            // 增加空值检查，避免空指针异常
            Point bodyPart = body.get(i);
            if (head != null && bodyPart != null && head.equals(bodyPart)) {
                return true;
            }
        }
        return false;
    }
    
    // Getters
    // 修改返回类型为 com.snakegame.entity.Point
    public Point getHead() {
        // 使用 getFirst() 替代 get(0)
        return ((LinkedList<Point>) body).getFirst();
    }
    
    public List<Point> getBody() {
        return body;
    }
    // 若确定该方法不会被使用，可以删除
    // public Direction getDirection() {
    //     return direction;
    // }

    public Direction getDirection() {
        return direction;
    }
}    